#include "apointer.h"
#include <mutex>
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
    redToFile("原数据");
    write_to_file("我也好");
    redToFile("新数据");
}
void write_to_file(const std::string &message)
{

    //创建互斥锁
    static std::mutex mutex;

    //在访问文件前进行加锁
    std::lock_guard<std::mutex> lock(mutex);

    //尝试打开文件
    std::ofstream file("test.txt");
    if (!file.is_open())
    {
        throw std::runtime_error("unable to open file : ./test.txt");
    }

    file << message << std::endl;
    printf("写入数据 : %s\n", &message);
}

void redToFile(const char *message)
{
    //创建互斥锁
    static mutex m;

    //在访问文件前进行加锁
    lock_guard<mutex> lock(m);

    ifstream file("test.txt");
    if (!file.is_open())
    {
        throw runtime_error("unable to open file : ./test.txt");
    }

    char str[20];
    file >> str;

    printf("%s : %s\n", message, str);
}